<template>
  <div class="i18n-selector" :style="showAnimation">
    <div class="back" @click="close"></div>
    <div class="front">
      <div class="box">
        <div class="header">
          <span>
            <!-- 国际化语言 -->
            {{ $srv.getI18nByPath('piece.oChartSetting.i18n') }}
          </span>
          <div class="close-btn" @click="close">
            <Icon type="ios-close" />
          </div>
          <Button
            class="save-btn"
            size="small"
            :disabled="saveDisabled"
            @click="save"
          >
            <!-- 保存 -->
            {{ $srv.getI18nByPath('others.save') }}
          </Button>
        </div>
        <div class="main">
          <div class="input-cell-f">
            <span>
              <!-- 原文 -->
              {{ $srv.getI18nByValue('关键字') }}
              :
            </span>
            <!-- placeholder="输入国际化原文" -->
            <AutoComplete
              v-model="name"
              :data="i18nArr"
              @on-search="searchI18nContent"
              @on-select="getI18nContent"
              @on-blur="onBlur"
              @on-change="onChange"
              :placeholder="$srv.getI18nByPath('oI18nPanel.enteri18noriginal')"
            ></AutoComplete>
          </div>
          <span class="input-cell-title">
            <!-- 语言列表 -->
            {{ $srv.getI18nByPath('oI18nPanel.languagelist') }}
            :
          </span>

          <div v-for="(item, key) in language" :key="key">
            <div class="input-cell">
              <span :class="{ 'input-cell-warn': item.warn }"
                >{{ item.label }}:</span
              >
              <i-input v-model="item.value"></i-input>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Tsrv, T_srv, vue } from '@/services';
import { i18n, langContext, VueI18n } from '@/config/i18n.config';

@T_srv.comp
export default class oI18nPanel extends vue {
  @T_srv.prop({ required: true }) config: any;

  @T_srv.prop({ required: true }) id: string;

  private compName: string = 'oI18nPanel';

  private name: string = '';

  public showAnimation: any = {};

  public language: any = {
    'zh-CN': {
      value: '',
      label: '简体中文',
      warn: false
    },
    'zh-TW': {
      value: '',
      label: '繁体中文',
      warn: false
    },
    'en-US': {
      value: '',
      label: '英文',
      warn: false
    }
  };

  public ifShowMore: boolean = false;

  public isFullLoaded: boolean = false;

  public i18nArr: Array<any> = [];

  public i18nData: Array<any> = [];

  public saveDisabled: boolean = true;

  public oldValue: Map<string, string> = new Map();

  public defLang: string = Tsrv.getSysDefLang();

  public i18nMsg: VueI18n.LocaleMessage = null;

  public keyLang: string = '';

  public keyI18nContent: VueI18n.LocaleMessage = null;

  public defLangI18nContext: VueI18n.LocaleMessage = null;

  private isInitOnce: boolean = false;

  get currentLang() {
    return this.$i18n.locale;
  }

  @T_srv.watch('language', { deep: true })
  onValChange(newV, oldV) {
    for (const key in this.language) {
      if (newV[key].value !== this.oldValue.get(key)) {
        this.saveDisabled = false;
        break;
      }
      this.saveDisabled = true;
    }
  }

  @T_srv.watch('name')
  onNameChange(newV, oldV) {
    if (newV !== this.oldValue.get('name')) {
      if (!Tsrv.utils.noValue(newV)) {
        this.saveDisabled = false;
      }
    } else {
      for (const o in this.language) {
        this.language[o].value = this.oldValue.get(o);
      }
      this.saveDisabled = true;
    }
  }

  public created() {}

  public initOnce() {
    if (this.isInitOnce || this.i18nMsg) {
      return;
    }

    this.i18nMsg = this.$i18n.messages;
    if (!this.i18nMsg) {
      return;
    }

    this.keyLang = this.i18nMsg['en-US']
      ? 'en-US'
      : Object.keys(this.i18nMsg)[0];

    this.keyI18nContent = this.i18nMsg[this.keyLang].i18n;

    this.defLangI18nContext =
      this.defLang && this.defLang !== this.keyLang
        ? this.i18nMsg[this.defLang].i18n
        : null;

    this.i18nData = Object.keys(this.keyI18nContent);
    if (!Tsrv.utils.noValue(this.defLangI18nContext)) {
      this.i18nData.forEach((ele, idx) => {
        this.i18nData[idx] = `${ele}[${this.defLangI18nContext[ele]}]`;
      });
    }
    this.isInitOnce = true;
  }

  public mounted() {
    this.loadmoreLang()
      .then(r => {
        if (r) {
          this.initOnce();
          this.show(this.config);
          this.saveOldVal();
        }
      })
      .catch(err => {
        throw new Error(err);
      });
  }

  public saveOldVal() {
    this.oldValue.set('zh-CN', this.language['zh-CN'].value);
    this.oldValue.set('zh-TW', this.language['zh-TW'].value);
    this.oldValue.set('en-US', this.language['en-US'].value);
    this.oldValue.set('name', this.name);
  }

  public loadmoreLang(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const lang = Object.keys(this.language);
      this.$languageSetter
        .loadLanguage(lang)
        .then(() => {
          resolve(true);
        })
        .catch(err => {
          reject(err);
        });
    });
  }

  public onBlur() {
    this.name = this.name.trim();
  }

  public savechk(): boolean {
    let isChange: boolean = false;
    for (const o in this.language) {
      const val = this.language[o].value;
      if (Tsrv.utils.noValue(val)) {
        this.$msg(Tsrv.getI18nByPath('oI18nPanel.fillallinfo'));
        this.language[o].warn = true;
        setTimeout(() => {
          this.language[o].warn = false;
        }, 1000);
        return false;
      }
      if (o === 'zh-TW' || o === 'zh-CN') {
        if (!this.cnCheck(val)) {
          this.$msg(Tsrv.getI18nByValue('允许中文|字母|数字'));
          this.language[o].warn = true;
          setTimeout(() => {
            this.language[o].warn = false;
          }, 1000);
          return false;
        }
      }
      if (o === 'en-US') {
        if (!this.enCheck(val)) {
          this.$msg(Tsrv.getI18nByValue('允许字母|数字|空格|下划线|点号'));
          this.language[o].warn = true;
          setTimeout(() => {
            this.language[o].warn = false;
          }, 1000);
          return false;
        }
      }
      if (this.oldValue.get(o) !== val && !isChange) {
        isChange = true;
      }
    }
    return isChange;
  }

  public save(): boolean {
    if (!this.savechk()) {
      return false;
    }
    if (Tsrv.utils.noValue(this.name)) {
      return false;
    }
    const lang: Array<{ lang: string; value: string }> = [];
    const langArr = [];
    this.name = this.name.trim();
    const that = this;

    Object.keys(that.language).forEach(key => {
      lang.push({
        lang: `${key}`,
        value: that.language[key].value
      });
      langArr.push(key);
    });
    const params = {
      key: that.name,
      data: lang
    };
    if (lang.length === 0) {
      this.$bus.$emit(`modal_${that.id}`, null);
      this.close();
      return false;
    }
    Tsrv.standardPostReq(params, Tsrv.url.setI18n)
      .then(([res, msg]) => {
        this.$msg(msg ?? res.msg);

        if (res.success && !msg) {
          that.$languageSetter.loadLanguage(langArr).then(() => {
            that.$bus.$emit(`modal_${that.id}`, that.name);
            that.saveDisabled = true;
            that.close();
          });
        }
      })
      .catch(err => {
        throw new Error(err);
      });

    return true;
  }

  public init(data) {
    this.name = Tsrv.utils.isEmpty(data.name) ? '' : data.name.trim();

    this.getI18nContent();
  }

  public searchI18nContent(val) {
    this.initOnce();
    if (Tsrv.utils.isString(val)) {
      this.i18nArr = this.i18nData.filter(
        el => el.toUpperCase().indexOf(val.toUpperCase()) !== -1
      );
    }
  }

  public getI18nContent(val?: string) {
    if (val) {
      val = val.trim();
      this.name = val.split('[')[0];
      this.name = this.getVerifyName(this.name);
    }
    Object.keys(this.language).forEach(key => {
      const v = Tsrv.getI18nBySrv(this.name, key);
      // 当国际化的值与国际化字段相同时，显示为空
      this.language[key].value = v === this.name ? '' : v;
      // this.language[key].value = v;
    });
  }

  public close() {
    const that = this;
    this.showAnimation = {
      opacity: 0,
      // 'z-index': 102 + this.id
      'z-index': 202 + this.id
    };
    setTimeout(() => {
      this.$bus.$emit(`modal_${this.id}`, null);
    }, 200);
  }

  public show(data) {
    const that = this;
    this.showAnimation = {
      // 'z-index': 102 + this.id
      'z-index': 202 + this.id
    };
    this.init(data);
    setTimeout(() => {
      that.showAnimation = {
        opacity: 1,
        // 'z-index': 102 + this.id
        'z-index': 202 + this.id
      };
    }, 10);
  }

  public getVerifyName(name) {
    // 不允许点号开头 不允许数字开头 允许字符 中间数字 中间点号
    return name.replace(/[^a-zA-Z_.\d]|(^\d.)|(^\..)/g, '');
  }

  // 禁止输入英文_
  public onChange() {
    this.$nextTick(() => {
      this.name = this.getVerifyName(this.name);
      this.getI18nContent(this.name);
    });
  }

  // 只输入中文 字母 和数字
  public cnCheck(val: string): boolean {
    return val === val.replace(/[^\u4E00-\u9FA5\da-zA-Z]/g, '');
  }

  // 只输入英文
  public enCheck(val): boolean {
    return val === val.replace(/[^a-zA-Z_.( )\d]|(^\d.)|(^\..)/g, '');
  }
}
</script>
<style scoped lang="scss">
//框架
.i18n-selector {
  position: absolute;
  z-index: 1001;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  transition: ease-in-out 0.2s;
  .back {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%;
  }
  .front {
    position: absolute;
    width: 500px;
    height: 600px;
    top: 50%;
    left: 50%;
    margin: -300px -250px;
    .box {
      width: 100%;
      height: 100%;
      background-color: var(--model-bg-color);
      display: flex;
      flex-direction: column;
      border-radius: var(--border-radius-model);
      overflow: hidden;
      .header {
        width: 100%;
        position: relative;
        height: 48px;
        background-color: rgba(244, 244, 244, 1);
        padding: 0 30px;
        box-shadow: var(--default-box-shadow-down);
        z-index: 11;
      }
      .main {
        width: 100%;
        flex: 1;
        overflow: hidden;
        padding: 10px 20px;
      }
    }
  }
}
.header {
  span {
    font-size: 14px;
    font-weight: bold;
    line-height: 46px;
    color: #666;
  }
  .save-btn {
    position: absolute;
    right: 73px;
    top: 11px;
    height: 26px;
    padding: 0 10px;
    border-radius: 3px;
    border: none;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
  }
  .close-btn {
    position: absolute;
    right: 30px;
    top: 10px;
    width: 28px;
    height: 28px;
    cursor: pointer;
    color: #666;
    .ivu-icon {
      font-size: 28px;
      font-weight: bold;
    }
  }
}
.main {
  .ivu-btn {
    border: none;
    float: right;
    margin: 6px 0;
    &:hover {
      background-color: #fff;
    }
  }
  .input-cell-f {
    padding: 0 10px;
    line-height: 30px;
    span {
      display: block;
    }
    ::v-deep .ivu-select-dropdown {
      max-height: 300px;
    }
  }
  .input-cell-title {
    margin: 10px 0 0 0;
    padding: 0 10px;
    display: block;
    line-height: 40px;
  }
  .input-cell {
    float: left;
    width: calc(100% - 20px);
    margin: 0 10px;
    overflow: hidden;
    border-bottom: 1px solid #eee;
    background-color: #f8f8f8;
    height: 40px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    .input-cell-c {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      flex: 1;
    }
    .input-cell-warn {
      border: 1px solid #f40;
    }

    span {
      width: 100px;
      line-height: 40px;
      background-color: #f5f5f5;
      float: left;
      text-align: left;
      border-right: 1px solid #eee;
      padding: 0 10px;
    }
    .ivu-input-wrapper ::v-deep {
      float: left;
      height: 40px;
      input {
        border: none;
        height: 40px;
        padding: 0 20px;
        background-color: transparent;
      }
    }
  }
}
</style>
